<template>
  <view class="home-container">
    <!-- 更新横幅 -->
    <UpdateBanner 
      :visible="showUpdateBanner"
      :updateInfo="updateInfo"
      @upgrade="handleUpgrade"
      @ignore="handleIgnore"
      @close="closeUpdateBanner"
    />
    
    <!-- 服务器状态组件 -->
    <ServerStatus 
      :serverStatus="serverStatus"
      :statusText="statusText"
      :networkInfo="networkInfo"
      :isRefreshing="isRefreshing"
      :showEnvInfo="showEnvInfo"
      :envInfo="envInfo"
      @refresh="refreshServerStatus"
    />
    
    <!-- 用户信息卡片组件 -->
    <UserInfoCard 
      :isLoggedIn="isLoggedIn"
      :userName="userName"
      :userAvatar="userAvatar"
      :isAdmin="isAdmin"
      @avatar-error="handleAvatarError"
      @admin-click="navigateToAdmin"
      @login="navigateToLogin"
      @register="navigateToRegister"
    />
    
    <!-- 公告横幅组件 -->
    <AnnouncementBanner 
      :announcements="announcements"
      @announcement-click="showAnnouncementDetail"
      @index-change="handleAnnouncementIndexChange"
    />
    
    <!-- 功能网格组件 -->
    <FunctionGrid 
      :isLoggedIn="isLoggedIn"
      @navigate="handleFunctionNavigate"
    />
    
    <!-- 数据同步弹窗 -->
    <DataSyncModal 
      :visible="showDataSyncModal"
      @close="closeDataSyncModal"
      @user-data-updated="onUserDataUpdated"
    />
    
    <!-- 桌面宠物组件 -->
    <DesktopPet 
      v-if="showDesktopPet"
      :pet-data="desktopPetData"
      :visible="desktopPetVisible"
      @pet-data-updated="onPetDataUpdated"
    />
  </view>
</template>

<script>
import apiService from '../../utils/api-service.js'
import appStateManager from '../../utils/app-state-manager.js'
import config from '../../utils/config.js'
import desktopPetManager from '../../utils/desktop-pet-manager.js'
import chatService from '../../utils/websocket-chat-service.js'
import autoUpdateChecker from '../../utils/update/auto-checker.js'
import wgtHotUpdate from '../../utils/wgt-hot-update.js'
import ServerStatus from './components/ServerStatus.vue'
import UserInfoCard from './components/UserInfoCard.vue'
import AnnouncementBanner from './components/AnnouncementBanner.vue'
import FunctionGrid from './components/FunctionGrid.vue'
import DataSyncModal from './components/DataSyncModal.vue'
import DesktopPet from '../../components/DesktopPet.vue'
import UpdateBanner from '../../components/UpdateBanner.vue'

export default {
  components: {
    ServerStatus,
    UserInfoCard,
    AnnouncementBanner,
    FunctionGrid,
    DataSyncModal,
    DesktopPet,
    UpdateBanner
  },
  data() {
    return {
      isLoggedIn: false,
      userName: '',
      userAvatar: '',
      userRole: '',
      isAdmin: false,
      serverStatus: 'checking',
      statusText: '正在检查服务器状态...',
      networkInfo: '',
      isRefreshing: false,
      envInfo: {},
      showEnvInfo: false,
      announcements: [],
      currentAnnouncementIndex: 0,
      showDataSyncModal: false,
      showDesktopPet: false,
      desktopPetVisible: true,
      desktopPetData: {},
      // 自动更新相关
      showUpdateBanner: false,
      updateInfo: {},
      isUpdating: false
    }
  },
  
  onLoad() {
    this.checkLoginStatus()
    const serverState = appStateManager.getState('server')
    this.serverStatus = serverState.isOnline ? 'online' : 'offline'
    this.statusText = serverState.isOnline ? '服务器连接正常' : '服务器连接异常'
    this.setupServerStatusListener()
    this.initEnvironmentInfo()
    this.loadAnnouncements()
    this.initDesktopPet()
    
    // 自动检查更新
    this.checkForUpdateAuto()
  },
  
  onShow() {
    this.checkLoginStatus()
    appStateManager.subscribe('server', (serverState) => {
      this.serverOnline = serverState.isOnline
    })
    this.loadAnnouncements()
  },
  
  onUnload() {
    this.cleanup()
  },
  
  methods: {
    // ========== 用户相关方法 ==========
    checkLoginStatus() {
      try {
        const token = uni.getStorageSync('user_token')
        const currentUser = uni.getStorageSync('currentUser')
        
        if (token && currentUser) {
          try {
            const userData = JSON.parse(currentUser)
            if (userData && userData.name) {
              this.isLoggedIn = true
              this.userName = userData.name
              this.userAvatar = userData.avatar || ''
              this.userRole = userData.role || 'user'
              this.isAdmin = userData.role === 'admin'
            } else {
              this.clearLoginData()
            }
          } catch (parseError) {
            this.clearLoginData()
          }
        } else {
          this.isLoggedIn = false
          this.userName = ''
        }
      } catch (error) {
        console.log('检查登录状态失败:', error)
        this.clearLoginData()
      }
    },
    
    clearLoginData() {
      this.isLoggedIn = false
      this.userName = ''
      this.userAvatar = ''
      this.userRole = ''
      this.isAdmin = false
      uni.removeStorageSync('user_token')
      uni.removeStorageSync('currentUser')
      uni.removeStorageSync('currentToken')
      uni.removeStorageSync('isServerLogin')
    },
    
    handleAvatarError() {
      this.userAvatar = ''
      console.log('头像加载失败，使用默认头像')
    },
    
    // ========== 导航方法 ==========
    navigateToLogin() {
      uni.navigateTo({ url: '/pages/auth/login/login' })
    },
    
    navigateToRegister() {
      uni.navigateTo({ url: '/pages/auth/register/register' })
    },
    
    navigateToAdmin() {
      uni.navigateTo({ url: '/pages/admin/admin' })
    },
    
    handleFunctionNavigate(type) {
      const routes = {
        sync: () => this.openDataSyncModal(),
        logs: '/pages/logs/logs',
        tts: '/pages/ai/voice/voice',
        emoji: '/pages/ai/emoji/emoji',
        pet: '/pages/pet/pet-settings',
        package: '/pages/package/list/list'
      }

      const route = routes[type]
      if (typeof route === 'function') {
        route()
      } else {
        uni.navigateTo({ url: route })
      }
    },
    
    // ========== 服务器状态方法 ==========
    updateServerStatusDisplay() {
      const status = appStateManager.getState("server")
      this.serverStatus = status.isOnline ? 'online' : 'offline'
      this.statusText = status.isOnline ? '服务器连接正常' : '服务器连接异常'
    },
    
    async refreshServerStatus() {
      if (this.isRefreshing) return
      
      this.isRefreshing = true
      try {
        await apiService.refreshServerStatus()
        this.updateServerStatusDisplay()
        const networkInfo = await apiService.getNetworkInfo()
        this.networkInfo = `网络: ${networkInfo.networkType}`
        
        uni.showToast({
          title: this.serverStatus === 'online' ? '服务器连接正常' : '服务器连接异常',
          icon: this.serverStatus === 'online' ? 'success' : 'none'
        })
      } catch (error) {
        console.error('刷新服务器状态失败:', error)
        uni.showToast({ title: '刷新失败', icon: 'error' })
      } finally {
        this.isRefreshing = false
      }
    },
    
    setupServerStatusListener() {
      apiService.onStatusChange((isOnline) => {
        if (this.serverStatus !== (isOnline ? 'online' : 'offline')) {
          console.log('首页收到服务器状态变化:', isOnline ? '在线' : '离线')
        }
        this.updateServerStatusDisplay()
      })
    },
    
    initEnvironmentInfo() {
      this.envInfo = config.getEnvironmentInfo()
      this.showEnvInfo = this.envInfo.isDevelopment
      console.log('环境信息:', this.envInfo)
    },
    
    // ========== 公告相关方法 ==========
    async loadAnnouncements() {
      try {
        const serverStatus = appStateManager.getState("server")
        if (!serverStatus.isOnline) {
          console.log('服务器离线，使用默认公告')
          this.setDefaultAnnouncements()
          return
        }
        
        console.log('开始加载公告数据...')
        const response = await apiService.getAdminAnnouncementList({
          page: 1,
          pageSize: 10,
          status: 'published'
        })
        
        if (response.code === 'SUCCESS' && response.data && response.data.announcements) {
          this.announcements = response.data.announcements
            .sort((a, b) => new Date(b.publish_time || b.created_at) - new Date(a.publish_time || a.created_at))
            .map(announcement => ({
              id: announcement.id,
              title: announcement.title,
              content: announcement.content,
              type: announcement.type,
              date: announcement.publish_time || announcement.created_at
            }))
          
          console.log('成功加载公告:', this.announcements.length, '条')
        } else {
          console.log('获取公告失败，使用默认公告')
          this.setDefaultAnnouncements()
        }
      } catch (error) {
        console.error('加载公告失败:', error)
        this.setDefaultAnnouncements()
      }
    },
    
    setDefaultAnnouncements() {
      this.announcements = [
        {
          id: 1,
          title: '🎉 欢迎使用新版用户管理系统！',
          content: '我们很高兴为您介绍全新升级的用户管理系统，带来更好的用户体验和更多实用功能。',
          type: 'welcome',
          date: '2024-01-15'
        },
        {
          id: 2,
          title: '🎮 游戏中心新增多个精彩游戏',
          content: '游戏中心现已上线，包含荒岛求生、益智拼图等多种游戏类型，更多游戏正在开发中！',
          type: 'feature',
          date: '2024-01-10'
        },
        {
          id: 3,
          title: '⚙️ 系统设置功能全面升级',
          content: '全新的设置页面设计，更直观的功能分类，让您轻松管理个人信息和系统偏好。',
          type: 'update',
          date: '2024-01-08'
        }
      ]
    },
    
    showAnnouncementDetail(announcement) {
      uni.showModal({
        title: announcement.title,
        content: announcement.content,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    handleAnnouncementIndexChange(index) {
      this.currentAnnouncementIndex = index
    },
    
    // ========== 数据同步相关方法 ==========
    openDataSyncModal() {
      this.showDataSyncModal = true
    },
    
    closeDataSyncModal() {
      this.showDataSyncModal = false
    },
    
    onUserDataUpdated(updatedUser) {
      console.log('收到用户数据更新通知:', updatedUser)
      uni.setStorageSync('currentUser', JSON.stringify(updatedUser))
      uni.showToast({ title: '用户信息已更新', icon: 'success', duration: 1500 })
    },
    
    // ========== 桌面宠物相关方法 ==========
    initDesktopPet() {
      try {
        this.desktopPetData = desktopPetManager.getPetData()
        this.showDesktopPet = this.desktopPetData.isActive
        
        desktopPetManager.on('pet-data-updated', (data) => {
          this.desktopPetData = data
          this.showDesktopPet = data.isActive
        })
        
        console.log('桌面宠物初始化成功:', this.desktopPetData.name)
      } catch (error) {
        console.error('桌面宠物初始化失败:', error)
      }
    },
    
    onPetDataUpdated(data) {
      this.desktopPetData = data
      console.log('宠物数据已更新:', data)
    },
    
    // ========== 自动更新相关方法 ==========
    async checkForUpdateAuto() {
      // #ifdef H5
      // H5平台不需要WGT更新，跳过检查（避免CORS错误）
      console.log('[首页] H5平台，跳过自动更新检查')
      return
      // #endif
      
      // #ifdef APP-PLUS
      // APP平台：完全复用设置页面的检查更新逻辑
      try {
        console.log('[首页] 开始自动检查更新...')
        
        // 配置Gitee信息（与设置页面完全一致）
        wgtHotUpdate.setGiteeConfig('xuxinzhi2206', 'moe_web', '')
        
        // 检查更新（与设置页面完全一致）
        const result = await wgtHotUpdate.checkForUpdate()
        
        // 记录检查时间（与设置页面完全一致）
        autoUpdateChecker.recordCheckTime()
        
        // 记录更新日志（与设置页面完全一致）
        autoUpdateChecker.logUpdateAction('check', {
          hasUpdate: result.hasUpdate,
          currentVersion: result.currentVersion,
          remoteVersion: result.remoteVersion,
          message: result.message
        })
        
        if (result.hasUpdate) {
          console.log('[首页] 发现新版本，显示横幅')
          this.updateInfo = result
          this.showUpdateBanner = true
        } else {
          console.log('[首页] 当前已是最新版本')
        }
      } catch (error) {
        console.error('[首页] 自动检查更新失败:', error)
        // 静默失败，不影响用户体验（与设置页面一致）
      }
      // #endif
    },
    
    async handleUpgrade() {
      if (this.isUpdating) {
        console.log('[首页] 更新正在进行中...')
        return
      }
      
      this.isUpdating = true
      this.showUpdateBanner = false
      
      try {
        // 记录升级操作
        autoUpdateChecker.logUpdateAction('upgrade', {
          version: this.updateInfo.remoteVersion
        })
        
        // 显示加载提示
        uni.showLoading({
          title: '准备更新...',
          mask: true
        })
        
        // 获取下载URL
        const downloadUrl = wgtHotUpdate.getDownloadUrl()
        console.log('[首页] 开始下载更新，URL:', downloadUrl)
        
        // 下载并应用更新
        await wgtHotUpdate.downloadAndApplyUpdate(
          downloadUrl,
          this.updateInfo,
          (progress) => {
            // 更新进度提示
            console.log('[首页] 更新进度:', progress)
            uni.showLoading({
              title: progress.message || '更新中...',
              mask: true
            })
          }
        )
        
        uni.hideLoading()
        
        // 提示重启
        uni.showModal({
          title: '更新成功',
          content: '更新已完成，需要重启应用才能生效',
          showCancel: false,
          confirmText: '立即重启',
          success: () => {
            wgtHotUpdate.restartApp()
          }
        })
        
      } catch (error) {
        console.error('[首页] 更新失败:', error)
        uni.hideLoading()
        
        // 记录失败日志
        autoUpdateChecker.logUpdateAction('upgrade_failed', {
          version: this.updateInfo.remoteVersion,
          error: error.message
        })
        
        uni.showModal({
          title: '更新失败',
          content: error.message || '更新过程中出现错误，请稍后重试',
          showCancel: true,
          confirmText: '重试',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.handleUpgrade()
            }
          }
        })
      } finally {
        this.isUpdating = false
      }
    },
    
    handleIgnore() {
      console.log('[首页] 用户选择稍后再说')
      
      // 记录忽略操作
      autoUpdateChecker.logUpdateAction('ignore', {
        version: this.updateInfo.remoteVersion
      })
      
      // 在当前会话中忽略此版本
      autoUpdateChecker.ignoreVersionInSession(this.updateInfo.remoteVersion)
      this.showUpdateBanner = false
    },
    
    closeUpdateBanner() {
      console.log('[首页] 用户关闭横幅')
      
      // 记录关闭操作
      autoUpdateChecker.logUpdateAction('close', {
        version: this.updateInfo.remoteVersion
      })
      
      this.showUpdateBanner = false
    },
    
    // ========== 清理资源 ==========
    cleanup() {
      if (this.announcementTimer) {
        clearInterval(this.announcementTimer)
        this.announcementTimer = null
      }
    }
  }
}
</script>

<style scoped>
/* ========== 主容器样式 ========== */
.home-container {
  min-height: calc(100vh - 188rpx);
  height: auto;
  background: linear-gradient(180deg, #f7f8fc 0%, #eef1f7 100%);
  padding: 20rpx;
  padding-bottom: 40rpx;
  box-sizing: border-box;
}


</style>

